import axios, { AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from './auth'

const noTokenPageWhiteList: any = []
const isDev = process.env.NODE_ENV === 'development'

const MAIN_API = isDev ? 'http://localhost:5555/api' : 'http://art.congming-ai.cn/api'


const httpRequest = axios.create()

export interface IRes<T = any> {
  code: number
  stat?: number
  data: T
  result?: T
  message: string
  success: boolean
}

httpRequest.defaults.baseURL = MAIN_API

const interceptorRequest = async (req: any) => {
  if (req.url === 'https://fonter.dancf.com/subset') {
    return req
  }
  if (!req?.headers?.accesstoken) {
    const accesstoken = getToken()

    if (accesstoken) {
      Object.assign(req.headers, { authorization: `Bearer ${accesstoken}` })
    }
  }

  return req
}

const interceptorResponse = (res: AxiosResponse<IRes>) => {
  if (res.data.code === 401) {
    setTimeout(() => {
      if (!noTokenPageWhiteList.includes(window.location.pathname)) {
        ElMessage('需要登录')
      }
    }, 2000)
  }

  if (res.data.code === 0 || res.data.code === 200) {
    return Promise.resolve(res.data)
  }

  if (!res.data || res.data.code !== 2000) {
    return Promise.reject(res.data)
  }
}

httpRequest.interceptors.request.use(interceptorRequest)
// 响应拦截器
httpRequest.interceptors.response.use(interceptorResponse, (error) => {
  return Promise.reject(error)
})

export default httpRequest
